from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.

from django.views.generic.base import View
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView
from rest_framework import viewsets
from .util import info, JwtToken
# Create your views here.
import requests
from .models import WeChatUser
from .auth import LoginAuth

APPID = 'wx403e7792cd17b5d9'
SECRET = '54dd671a2aff1a570d3d15d5973a661f'

def GetUserID(request):
    l = LoginAuth()
    userUID = l.authenticate(request)
    user = WeChatUser.objects.get(uuid=userUID)
    # 获取用户是否被拉入黑名单
    if user.id_delete==True:
        return info(status=201, message="用户已被拉入黑名单")
    return user.id

class UserAuth(APIView):

    def post(self, request):
        data = request.data
        # 获取前端传过来的code
        JSCODE = data.get('code')
        if JSCODE:
            try:
                # 换取微信登录凭证
                wx_url = 'https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code'.format(
                    APPID, SECRET, JSCODE)
                wx_res = requests.get(wx_url).json()
            except Exception as e:
                return info(status=0, message=str(e))

            try:
                # 查询数据库是否有该用户
                ent = WeChatUser.objects.filter(uuid=wx_res['openid']).exists()
                # 判断没有该用户则创建该用户
                if not ent:
                    user = WeChatUser()
                    user.uuid = wx_res['openid']
                    user.username = data.get('username')
                    user.gender = data.get('gender')
                    user.province = data.get('province')
                    user.city = data.get('city')
                    user.image = data.get('avatarUrl')
                    user.save()
                user = WeChatUser.objects.get(uuid=wx_res['openid'])
                if user.id_delete == True:
                    return info(status=201, message="用户已被拉入黑名单")
                # 初始化jwt_token
                token_obj = JwtToken()
                token = token_obj.encode_token({'uuid': wx_res['openid']})
                user = WeChatUser.objects.get(uuid=wx_res['openid'])
                user = model_to_dict(user)
                # 返回给用户
                return info(data={'token': token,
                                  'user':user
                                  })
            except:
                return info(status=0, message='服务器内部错误')
        return info(status=0, message='未获取到code')

    # 获取用户信息
    def get(self, request):
        data = request.GET
        # try:
        #     userID = GetUserUID(request)
        # except:
        #     return info(status=0, message="token失效或错误")
        try:

            user = WeChatUser.objects.get(id=data.get('userId'))
            user = model_to_dict(user)
            return info(status=200, message="获取成功", data={
                'data': user
            })
        except:
            return info(status=0, message="服务繁忙")


class UserDescView(APIView):
    def post(self, request):
        data = request.data
        try:
            userID = GetUserID(request)
        except:
            return info(status=0, message="token失效或错误")
        try:

            user = WeChatUser.objects.get(id=userID)
            user.desc = data.get("desc")
            user.save()
            user = model_to_dict(user)
            return info(status=200, message="提交成功", data={
                'data': user
            })
        except:
            return info(status=0, message="服务繁忙")


